//
//  ZLMvDetailViewController.m
//  环信
//
//  Created by 张琳 on 16/3/19.
//  Copyright © 2016年 LiTong. All rights reserved.
//

#import "ZLMvDetailViewController.h"


@interface ZLMvDetailViewController ()<UITableViewDataSource, UITableViewDelegate, HeaderIamgePushDelegate>

@property (nonatomic, retain) UIView *playView; /**< 播放视图 */
@property (nonatomic, retain) UIButton *downLoadButton;/**< 下载按钮 */
@property (nonatomic, retain) AVPlayer *player; /**< 播放器对象 */
@property (nonatomic, retain) AVPlayerItem *playerItem; /**< 播放项目 */
@property (nonatomic, retain) AVPlayerLayer *playerLayer; /**<  用于显示播放器 */

@property (nonatomic, retain) UIView *bottomView; /**< 底部视图 */
@property (nonatomic, retain) UIButton *playButton; /**< 播放按钮 */
@property (nonatomic, retain) UIButton *fullButton; /**< 全屏按钮 */
@property (nonatomic, retain) UIButton *backButton; /**< 返回按钮 */


@property (nonatomic, retain) UISlider *progressSlider; /**< 进度滑竿 */
@property (nonatomic, retain) UILabel *timeLable; /**< 时间 */

@property (nonatomic, assign) BOOL isPlay; /**< 是否进入播放状态 */
@property (nonatomic, assign) BOOL isHideen; /**< 是否隐藏 */

@property (nonatomic, assign) CGFloat totalDuration; /**< 视频播放总时长 */

@property (nonatomic, retain) UISegmentedControl *aboutSegment;/**< 三个segment */
@property (nonatomic, retain) UITableView *aboutTableView;/**< segment的下的tableview */
@property (nonatomic, retain) NSMutableArray *headImageArray;/**< 头像数组 */
@property (nonatomic, retain) NSDictionary *describeDic;
@property (nonatomic, retain) NSMutableArray *aboutMvArray;/**< 相关MV */
@property (nonatomic, retain) NSMutableArray *talkArray;/**< 谈论 */
@property (nonatomic, assign) BOOL isUpLoading;
@property (nonatomic, assign) NSInteger page;

@property (nonatomic, retain) NSString *URL;
@property (nonatomic, retain) NSString *buttonTittle;/**< 按钮的文字 */
@property (nonatomic, retain) UISegmentedControl *discoverSegmented;/**< 创建选择清晰度按钮 */

@property (nonatomic, retain) UIImageView *backViewImage;/**< 背景图 */
@property (nonatomic, strong) UIVisualEffectView *visualEfView;/**< 毛玻璃 */
@property (nonatomic, retain) UIView *blackView;/**< 背景图 */

@property (nonatomic, assign) NSInteger count;/**< 下载按钮点击计数 */

@property (nonatomic,retain) NSURLSessionDownloadTask *downLoadTask;/**< 下载任务 */

@property (nonatomic , strong) NSString *filePath;/**< 文件路径 */

// LXC 添加
@property (nonatomic, retain) NSMutableArray *arrFile; /**< 从文件取出来的数组 */
@property (nonatomic, retain) NSMutableArray *arrData; /**< 最开始从文件里面取出来的数组 */

@end

@implementation ZLMvDetailViewController
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.isPlay = YES;
        self.isHideen = NO;
        //赋初值，提升用户体验
        self.progressSlider.value = 0;
        self.timeLable.text = @"-:-/-.-";
        _buttonTittle = @"标清";
        self.arrFile = [NSMutableArray array];
    }
    return self;
}
- (void)viewWillAppear:(BOOL)animated {
    self.navigationController.navigationBar.barTintColor = [UIColor clearColor];

}
- (void)viewDidLoad {
    [super viewDidLoad];
    /**创建背景图 */
    [self createBackViewImage];
    /**创建毛玻璃 */
    [self createUnClearView];
    /**创建衬托view */
    [self createBlackView];

    [LXCPLAYSHARE pause];
    


    // Do any additional setup after loading the view.
    self.navigationController.navigationBar.hidden = NO;
    self.view.backgroundColor = [UIColor clearColor];
    self.describeDic = [NSDictionary dictionary];
    /**最底层图片 */
    UIImageView *backViewImage = [[UIImageView alloc] init];
    [backViewImage sd_setImageWithURL:[NSURL URLWithString:_model.albumImg]placeholderImage:[UIImage imageNamed:@"16.jpg"]];
    [self.view addSubview:backViewImage];
    self.headImageArray = [NSMutableArray array];
    self.aboutMvArray = [NSMutableArray array];
    self.talkArray = [NSMutableArray array];
    
    [self createButton];
    [self addAVPlayer];
    [self.player play];
    [self addProgressObserver];
    [self hidentBottomView];
    /**创建segment */
    [self createSegment];
    [self createTableView];

    /**数据解析 */
    [self dataHandle];
    



    
}
#pragma mark - 创建黑色衬托
- (void)createBlackView {
    self.blackView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    _blackView.backgroundColor = [UIColor blackColor];
    _blackView.alpha = 0.6;
    [_visualEfView addSubview:_blackView];
}
#pragma mark - 创建毛玻璃
- (void)createUnClearView {
    self.visualEfView = [[UIVisualEffectView alloc] initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleLight]];
    _visualEfView.frame = CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height);
    _visualEfView.alpha = 1;
    _visualEfView.userInteractionEnabled = YES;
    [_backViewImage addSubview:_visualEfView];
}
#pragma mark - 创建背景图
- (void)createBackViewImage {
    self.backViewImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    [self.view addSubview:_backViewImage];
    _backViewImage.userInteractionEnabled = YES;
    [_backViewImage sd_setImageWithURL:[NSURL URLWithString:_model.albumImg]];
    
}
- (void)addHeader {
    __block ZLMvDetailViewController *vc = self;
    [_aboutTableView addHeaderWithCallback:^{
        vc.page = 0;
        vc.isUpLoading = NO;
        [vc talkDataHandle];
    }];
    [self.aboutTableView headerBeginRefreshing];
    
}
- (void)addFoodter {
    __block ZLMvDetailViewController *vc = self;
    [_aboutTableView addFooterWithCallback:^{
        vc.page += 20;
        vc.isUpLoading = YES;
        [vc talkDataHandle];
    }];
    
}
#pragma mark - 数据处理
- (void)dataHandle {
    
    NSString *url = [NSString stringWithFormat:@"http://mapi.yinyuetai.com/video/show.json?D-A=0&id=%@&relatedVideos=true&supportHtml=false&v=2", _model.idValue];
    
    NSDictionary *dic = @{@"App-Id":@"10101027",@"Device-Id":@"29e4f1a25a431e3fa86484a58e218127",@"Device-V":@"aVBob25lIE9TXzkuMi4xXzY0MCoxMTM2XzEwMDAwMTAwMF9pUGhvbmU2LDI="};
    
    [XRAFNetworkTool GETUrl:url body:nil headFile:dic response:XRJSON success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"解析成功");
        
        _describeDic = responseObject;
        NSLog(@"%@", _describeDic[@"id"]);
        
        NSArray *array = responseObject[@"artists"];
        for (NSDictionary *dic in array) {
            ZLAllVideoDetailModel *model = [[ZLAllVideoDetailModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [_headImageArray addObject:model];
        }

        NSArray *aboutMv = responseObject[@"relatedVideos"];
        for (NSDictionary *dic in aboutMv) {
            ZLAllVideoDetailModel *model = [[ZLAllVideoDetailModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [_aboutMvArray addObject:model];
        }
        [_aboutTableView reloadData];

        
        
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"解析失败");
    }];
    
}
#pragma mark- 评论信息数据解析
- (void)talkDataHandle {
//    NSString *talkUrl = @"http://mapi.yinyuetai.com/video/comment/list.json?D-A=0&offset=0&size=20&v=2&videoId=%@", _describeDic[@"id"];
    NSString *talkUrl = [NSString stringWithFormat:@"http://mapi.yinyuetai.com/video/comment/list.json?D-A=0&offset=%ld&size=20&v=2&videoId=%@",_page, _describeDic[@"id"]];
    
    NSLog(@"hahahahhahahahaha%@", talkUrl);
    
    NSDictionary *dic = @{@"App-Id":@"10101027",@"Device-Id":@"29e4f1a25a431e3fa86484a58e218127",@"Device-V":@"aVBob25lIE9TXzkuMi4xXzY0MCoxMTM2XzEwMDAwMTAwMF9pUGhvbmU2LDI="};
    [XRAFNetworkTool GETUrl:talkUrl body:nil headFile:dic response:XRJSON success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"解析成功");
        NSArray *arr = responseObject[@"comments"];
        if ((_isUpLoading = NO)) {
            [_talkArray removeAllObjects];
        }
        
        for (NSDictionary *dic in arr) {
            ZLAboutMvModel *model = [[ZLAboutMvModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [_talkArray addObject:model];
        }
        [_aboutTableView headerEndRefreshing];
        [_aboutTableView footerEndRefreshing];
        [_aboutTableView reloadData];
        
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"解析失败");
    }];
    
    
}
#pragma mark - 评论 相关MV的tableview
- (void)createTableView {
    self.aboutTableView =[[UITableView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(_aboutSegment.frame) + 5, SCREEN_WIDTH, SCREEN_HEIGHT - CGRectGetMaxY(_aboutSegment.frame) - 50)];
    _aboutTableView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:_aboutTableView];
    
    /**代理 */
    _aboutTableView.delegate = self;
    _aboutTableView.dataSource = self;
    /**注册 */
    [_aboutTableView registerClass:[ZLMVDescribeTableViewCell class] forCellReuseIdentifier:@"ZLMVDescribeTableViewCell"];
    [_aboutTableView registerClass:[ZLAboutMvTableViewCell class] forCellReuseIdentifier:@"ZLAboutMvTableViewCell"];
    [_aboutTableView registerClass:[ZLTalkMVTableViewCell class] forCellReuseIdentifier:@"ZLTalkMVTableViewCell"];
}
#pragma mark - tableView的协议方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (_aboutSegment.selectedSegmentIndex == 0) {
           return _headImageArray.count;
    }else if (_aboutSegment.selectedSegmentIndex == 2) {
        return _aboutMvArray.count;
    }else {
        return _talkArray.count;
    }
    return 0;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_aboutSegment.selectedSegmentIndex == 0) {
        ZLMVDescribeTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ZLMVDescribeTableViewCell"];
        ZLAllVideoDetailModel *model = _headImageArray[indexPath.row];
        cell.headImageModel = model;
        cell.backgroundColor = [UIColor clearColor];
        cell.delegate = self;
        cell.describeDic = _describeDic;
        cell.selectionStyle = UITableViewCellAccessoryNone;
        return cell;
    }else if (_aboutSegment.selectedSegmentIndex == 2){
        ZLAboutMvTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ZLAboutMvTableViewCell"];
        ZLMvModel *model = _aboutMvArray[indexPath.row];
        cell.backgroundColor = [UIColor clearColor];
        cell.model = model;
        cell.selectionStyle = UITableViewCellAccessoryNone;

        return cell;
    }else {
        ZLTalkMVTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ZLTalkMVTableViewCell"];
        ZLAboutMvModel *model = _talkArray[indexPath.row];
        cell.model = model;
        cell.backgroundColor = [UIColor clearColor];
        cell.selectionStyle = UITableViewCellAccessoryNone;
        return cell;
    }


}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_aboutSegment.selectedSegmentIndex == 0) {
        CGSize size = CGSizeMake(SCREEN_WIDTH - 20, 100000);
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:12], NSFontAttributeName, nil];
        CGRect rect = [_describeDic[@"description"] boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
        return 140 + rect.size.height + 10;
    }else if (_aboutSegment.selectedSegmentIndex ==1 ) {
        ZLAboutMvModel *model = _talkArray[indexPath.row];
        
        CGSize size = CGSizeMake(SCREEN_WIDTH - 20, 100000);
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:12], NSFontAttributeName, nil];
        
        CGRect rect = [model.content boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
        
        return 65 + rect.size.height;
    }
    return 100;
}
#pragma mark - 相关视频点击方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_aboutSegment.selectedSegmentIndex == 2) {
        

    ZLAllVideoDetailModel *model = _aboutMvArray[indexPath.row];
//    ZLMvDetailViewController *vc = [[ZLMvDetailViewController alloc] init];
//    vc.model = model
    [_playView removeFromSuperview];
    [_playerLayer removeFromSuperlayer];
    _model.url = model.url;
    [self createButton];
    [self addAVPlayer];
    [self.player play];
    [self addProgressObserver];
    [self hidentBottomView];
//    [_playView reloadInputViews];
    }
}


#pragma mark - 创建segment
- (void)createSegment {
    self.aboutSegment = [[UISegmentedControl alloc] initWithItems:@[@"MV简介", @"评论", @"相关MV"]];
    _aboutSegment.frame = CGRectMake(10, CGRectGetMaxY(_playView.frame) + 5, SCREEN_WIDTH - 20, 30);
    _aboutSegment.selectedSegmentIndex = 0;
    [self.view addSubview:_aboutSegment];
    _aboutSegment.tintColor = [UIColor colorWithRed:0.32 green:0.75 blue:0.8 alpha:1];
    [_aboutSegment addTarget:self action:@selector(discoverSegmentValueChangedAction:) forControlEvents:UIControlEventValueChanged];
    
}
//segmented值变化方法
- (void)discoverSegmentValueChangedAction:(UISegmentedControl *)discoverSegmentChanged {
        
    if (_aboutSegment.selectedSegmentIndex == 0) {
        [self dataHandle];
    }else if (_aboutSegment.selectedSegmentIndex == 2) {
        [self dataHandle];
    }else {
        [self addHeader];
        [self addFoodter];
        
    }
}
/** 创建按钮 */
-(void)createButton {
    
    self.playView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 180)];
    _playView.backgroundColor = [UIColor blackColor];
    [self.view addSubview:_playView];
    
    self.downLoadButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _downLoadButton.frame = CGRectMake(SCREEN_WIDTH - 50, 80, 50, 30);
    _downLoadButton.titleLabel.font = [UIFont systemFontOfSize:15];
    _downLoadButton.layer.cornerRadius = 6;
    _downLoadButton.layer.masksToBounds = YES;
    _downLoadButton.backgroundColor = [UIColor blackColor];
    _downLoadButton.alpha = 0.6;
    [_downLoadButton setTitle:@"下载" forState:UIControlStateNormal];
    [_downLoadButton addTarget:self action:@selector(downLoadButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [_playView addSubview:_downLoadButton];
    
    
    self.bottomView = [[UIView alloc] init];
    if ([UIScreen mainScreen].bounds.size.height == 480) {
        _bottomView.frame = CGRectMake(0, SCREEN_HEIGHT / 3 - 15, SCREEN_WIDTH, 30);
    }else if ([UIScreen mainScreen].bounds.size.height == 736){
        _bottomView.frame = CGRectMake(0, SCREEN_HEIGHT / 3 - 95, SCREEN_WIDTH, 30);
    }else if ([UIScreen mainScreen].bounds.size.height == 667){
        _bottomView.frame = CGRectMake(0, SCREEN_HEIGHT / 3 - 70, SCREEN_WIDTH, 30);
    }else {
        _bottomView.frame = CGRectMake(0, SCREEN_HEIGHT / 3 - 40, SCREEN_WIDTH, 30);
    }
    _bottomView.alpha = 0.8;
    _bottomView.backgroundColor = [UIColor blackColor];
    [self.playView addSubview:_bottomView];
    
    self.playButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _playButton.frame = CGRectMake(3, 3 , 25, 25);
    [_playButton setTitleColor:[UIColor groupTableViewBackgroundColor] forState:UIControlStateNormal];
    [_playButton setImage:[UIImage imageNamed:@"videoplayer_pause@2x.png"] forState:UIControlStateNormal];
    [_playButton addTarget:self action:@selector(playButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [_bottomView addSubview:_playButton];
    
    self.progressSlider = [[UISlider alloc] initWithFrame:CGRectMake(5 + _playButton.frame.size.width + 5, 10, SCREEN_WIDTH - 20 - self.timeLable.frame.size.width - _playButton.frame.size.width - 100, 10)];
    [_progressSlider setThumbImage:[UIImage imageNamed:@"iconfont-zhinengshoubiao3-2.png"] forState:UIControlStateNormal];
    [_progressSlider addTarget:self action:@selector(progressSliderAction:) forControlEvents:UIControlEventTouchUpInside];
    [_bottomView addSubview:_progressSlider];
    
    self.timeLable = [[UILabel alloc] initWithFrame:CGRectMake(_playButton.frame.origin.x + 10 + _progressSlider.frame.size.width + 10 + 20, 3, 80, 30)];
    _timeLable.font = [UIFont systemFontOfSize:11];
    _timeLable.textColor = [UIColor whiteColor];
    [_bottomView addSubview:_timeLable];
    
//    UIButton *chooseClearButton = [UIButton buttonWithType:UIButtonTypeCustom];
//    chooseClearButton.frame = CGRectMake(10, 64, 50, 30);
//    chooseClearButton.backgroundColor = [UIColor whiteColor];
//    [chooseClearButton addTarget:self action:@selector(changeClearAction:) forControlEvents:UIControlEventTouchUpInside];
//    [_playView addSubview:chooseClearButton];
//    NSString *titleName =_buttonTittle;
//    [chooseClearButton setTitle:titleName forState:UIControlStateNormal];
//    [chooseClearButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    
    self.fullButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _fullButton.frame = CGRectMake(SCREEN_WIDTH - 35, 5 , 25, 25);
    [_fullButton setImage:[UIImage imageNamed:@"videoplayer_expand@2x.png"] forState:UIControlStateNormal];
    [_fullButton addTarget:self action:@selector(fullButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [_bottomView addSubview:_fullButton];
}
#pragma mark - 下载按钮方法
- (void)downLoadButtonAction:(UIButton *)button {
    
    NSString *temp = NSTemporaryDirectory();
    // 拼接最后存储的路径
    NSString *path = [temp stringByAppendingPathComponent:@"mv.plist"];
    NSLog(@"文件路径 : %@", path);

    // 按这个路径取出数组
    self.arrData = [NSMutableArray arrayWithContentsOfFile:path];
    for (NSDictionary *dic in self.arrData) {
        
        if ([dic.allKeys.firstObject isEqualToString:_model.title]) {
            [MBProgressHUD showInfoWithText:@"已经下载过了"];
            return;
        }
    }
    
    _downLoadButton.frame = CGRectMake(SCREEN_WIDTH - 100, 10, 80, 50);
    if (_count % 2 == 0) {
        
        [_downLoadButton setTitle:@"下载中" forState:UIControlStateNormal];

        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        _downLoadTask = [manager downloadTaskWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:_model.url]] progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
            
            NSFileManager *manager = [NSFileManager defaultManager];
            NSString *temp = NSTemporaryDirectory();
            NSString *path = [temp stringByAppendingPathComponent:@"mvDownLoad"];
            [manager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
            NSString *name = [NSString stringWithFormat:@"%@.mp4", _model.title];
            // 拼接最后存储的路径
            self.filePath = [path stringByAppendingPathComponent:name];
            NSURL *url = [NSURL fileURLWithPath:_filePath];
            NSLog(@"文件路径 : %@",_filePath);
            
            if (_filePath) {

                [_downLoadButton setTitle:@"下载完成" forState:UIControlStateNormal];

            }
            dispatch_async(dispatch_get_main_queue(), ^{
                // 方进度条
                
            });
            
            return url;
           
        } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
            
            // 按这个路径取出数组
            self.arrFile = [NSMutableArray arrayWithContentsOfFile:path];
            if (!self.arrFile) {
                self.arrFile = [NSMutableArray array];
            }
            
            // 生成字典 存进数组
            NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:_model.title, _model.title, nil];
            
            [self.arrFile addObject:dic];
            [self.arrFile writeToFile:path atomically:YES];

            
        }];
        /**任务开始 */
        [_downLoadTask resume];
        
        _count ++;
        
    }else {

        [_downLoadButton setTitle:@"暂停" forState:UIControlStateNormal];

        /**任务暂停 */
        [_downLoadTask suspend];
        
        _count ++;
        
    }
    
}


- (void)creta {
    
    self.playView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 180)];
    _playView.backgroundColor = [UIColor blackColor];
    [self.view addSubview:_playView];
}
/** 全屏放大 */
- (void)fullButtonAction:(UIButton *)button {
//    _aboutSegment.hidden = YES;
//    _aboutTableView.hidden = YES;
    [_fullButton setImage:[UIImage imageNamed:@"videoplayer_shrink@2x.png"] forState:UIControlStateNormal];
    self.navigationController.tabBarController.tabBar.hidden = YES;
    self.navigationController.navigationBar.hidden = YES;
    
    if ([UIDevice currentDevice].orientation != UIDeviceOrientationPortrait) {
        
        _aboutSegment.hidden = NO;
        _aboutTableView.hidden = NO;
        _downLoadButton.hidden = NO;
        
    [_fullButton setImage:[UIImage imageNamed:@"videoplayer_expand@2x.png"] forState:UIControlStateNormal];
        self.navigationController.tabBarController.tabBar.hidden = NO;
        self.navigationController.navigationBar.hidden = NO;
        
        NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationPortrait];
        [[UIDevice currentDevice] setValue:value forKey:@"orientation"];
        
        self.playView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 180);
        
        self.downLoadButton = [UIButton buttonWithType:UIButtonTypeCustom];
        _downLoadButton.frame = CGRectMake(SCREEN_WIDTH - 50, 80, 50, 30);
        _downLoadButton.titleLabel.font = [UIFont systemFontOfSize:15];
        _downLoadButton.layer.cornerRadius = 6;
        _downLoadButton.layer.masksToBounds = YES;
        _downLoadButton.backgroundColor = [UIColor blackColor];
        _downLoadButton.alpha = 0.6;
        [_downLoadButton setTitle:@"下载" forState:UIControlStateNormal];
        [_downLoadButton addTarget:self action:@selector(downLoadButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        [_playView addSubview:_downLoadButton];
        
        if ([UIScreen mainScreen].bounds.size.height == 480) {
            _bottomView.frame = CGRectMake(0, SCREEN_HEIGHT / 3 - 10, SCREEN_WIDTH, 30);
        }else if ([UIScreen mainScreen].bounds.size.height == 736){
            _bottomView.frame = CGRectMake(0, SCREEN_HEIGHT / 3 - 95, SCREEN_WIDTH, 30);
        }else if ([UIScreen mainScreen].bounds.size.height == 667){
            _bottomView.frame = CGRectMake(0, SCREEN_HEIGHT / 3 - 70, SCREEN_WIDTH, 30);
        }else {
            _bottomView.frame = CGRectMake(0, SCREEN_HEIGHT / 3 - 40, SCREEN_WIDTH, 30);
        }
        
        _aboutTableView.frame = CGRectMake(0, CGRectGetMaxY(_aboutSegment.frame) + 5, SCREEN_WIDTH, SCREEN_HEIGHT - CGRectGetMaxY(_aboutSegment.frame) - 50);
        
        self.playerLayer.frame = CGRectMake(0, 0, self.playView.frame.size.width, self.playView.frame.size.height);
        
        _playButton.frame = CGRectMake(3, 3 , 25, 25);
        
        self.progressSlider.frame = CGRectMake(5 + _playButton.frame.size.width + 5, 10, SCREEN_WIDTH - 20 - self.timeLable.frame.size.width - _playButton.frame.size.width , 10);
        
        self.timeLable.frame = CGRectMake(_playButton.frame.origin.x + 10 + _progressSlider.frame.size.width + 10 + 20, 3, 80, 30);
        
        self.fullButton.frame = CGRectMake(SCREEN_WIDTH - 35, 5 , 25, 25);
        
    }else {
        _downLoadButton.hidden = YES;
        _aboutSegment.hidden = YES;
        _aboutTableView.hidden = YES;
        _aboutTableView.frame = CGRectMake(0, 0, 0, 0);
        NSNumber *value = [NSNumber numberWithInt:UIInterfaceOrientationLandscapeRight];
        [[UIDevice currentDevice] setValue:value forKey:@"orientation"];
        self.playerLayer.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
        self.playView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
        //全屏后底部处理
        self.bottomView.frame = CGRectMake(0, SCREEN_HEIGHT * 5 / 6, SCREEN_WIDTH, SCREEN_HEIGHT / 6);
        
        //全屏后的播放功能view
        self.view.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
        //视频大小
        self.playerLayer.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
        //视频进度条 总时间 全屏按钮
        self.playButton.frame = CGRectMake(10, 10, 50, 50);
        self.progressSlider.frame = CGRectMake(_playButton.frame.size.width + 10, 26, SCREEN_WIDTH - 20 - self.timeLable.frame.size.width - _playButton.frame.size.width - 100, 20);
        self.timeLable.frame = CGRectMake(_playButton.frame.origin.x + 30 + _progressSlider.frame.size.width + 20 + 20, 12, 100, 50);
        self.fullButton.frame = CGRectMake(SCREEN_WIDTH - 50, 15 , 30, 30);
        
    }
}
#pragma mark - 改变清晰度方法
//- (void)changeClearAction:(UIButton *)button {
//    /**创建segment选择清晰度 */
//    [self createSegmentedControl];
//    
//
//    
//    
//}
//    //创建segmented方法实现
//- (void)createSegmentedControl {
//        /** 创建segmented */
//        UISegmentedControl *discoverSegmented = [[UISegmentedControl alloc] initWithItems:@[@"标清", @"高清", @"超清"]];
//        discoverSegmented.frame = CGRectMake(0, 64, SCREEN_WIDTH, 30);
//        [self.view addSubview:discoverSegmented];
//        discoverSegmented.backgroundColor = [UIColor blackColor];
//        /** 设置segmented边框颜色 */
//        discoverSegmented.tintColor = [UIColor clearColor];
//        /** 初始化新创建的字典、设置segmented字体 */
//        NSDictionary *discoverSegmentedTextBlackDic = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:18],NSForegroundColorAttributeName:[UIColor whiteColor]};
//        /** 把字典的值  给segmentControl  注意 setTitleTextAttributes 需要一个字典 */
//        [discoverSegmented setTitleTextAttributes:discoverSegmentedTextBlackDic forState:UIControlStateNormal];
//        /** 设置点击后的颜色 */
//        NSDictionary *discoverSegmentedTextRedDic = @{NSFontAttributeName:[UIFont boldSystemFontOfSize:18],NSForegroundColorAttributeName:[UIColor blueColor]};
//        /** 把字典的值  给segmentControl  注意 setTitleTextAttributes 需要一个字典 */
//        [discoverSegmented setTitleTextAttributes:discoverSegmentedTextRedDic forState:UIControlStateSelected];
//        /** 分段索引 */
//        discoverSegmented.selectedSegmentIndex = 0;
//        /** valueChanged 值发生变化  执行方法 */
//        [discoverSegmented addTarget:self action:@selector(discoverSegmentChangedClearAction:) forControlEvents:UIControlEventValueChanged];
//    }
////segmented值变化方法
//- (void)discoverSegmentChangedClearAction:(UISegmentedControl *)discoverSegmentChanged {
//    if (_discoverSegmented.selectedSegmentIndex == 0) {
//        [_playView removeFromSuperview];
//        [_playerLayer removeFromSuperlayer];
//        _model.url = _model.url;
//        [self createButton];
//        [self addAVPlayer];
//        [self.player play];
//        [self addProgressObserver];
//        [self hidentBottomView];
//    }else if (_discoverSegmented.selectedSegmentIndex == 1) {
//        [_playView removeFromSuperview];
//        [_playerLayer removeFromSuperlayer];
//        _model.url = _model.hdUrl;
//        [self createButton];
//        [self addAVPlayer];
//        [self.player play];
//        [self addProgressObserver];
//        [self hidentBottomView];
//        
//        
//    }else {
//        [_playView removeFromSuperview];
//        [_playerLayer removeFromSuperlayer];
//        _model.url = _model.shdUrl;
//        [self createButton];
//        [self addAVPlayer];
//        [self.player play];
//        [self addProgressObserver];
//        [self hidentBottomView];
//
//    }
//    
//    
//}
//


/** 添加播放器 */
- (void)addAVPlayer {
    
    NSURL *URL = [NSURL URLWithString:_model.url];
    
    //创建播放项目对象
    self.playerItem = [AVPlayerItem playerItemWithURL:URL];
    
//    创建播放器对象
    self.player = [AVPlayer playerWithPlayerItem:self.playerItem];
    
//    AVPlayerViewController *VC = [AVPlayerViewController new];
//    VC.view.frame = CGRectZero;
//    
//    VC.player = [AVPlayer playerWithPlayerItem:self.playerItem];
    
    
//    创建承载播放器的layer
    self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
    self.playerLayer.frame = CGRectMake(0, 0, self.playView.frame.size.width, self.playView.frame.size.height);
    
    self.playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    [self.playView.layer insertSublayer:self.playerLayer atIndex:0];
//    [self.playView.layer addSublayer:self.playerLayer];
    
  

    
}

/** 播放进度监听 */
- (void)addProgressObserver {
    [self.player addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
        //获取总时间(self.playerItem.duration 播放时长)
        CGFloat duration = CMTimeGetSeconds(_playerItem.duration);
        self.totalDuration = duration;
        //获取当前时间
        CGFloat current = CMTimeGetSeconds(self.playerItem.currentTime);
        //把总时间转化为字符串显示在label上
        NSString *durrationTimeStr = [NSString stringWithFormat:@"%02d:%02d", (int)duration / 60, (int)duration % 60];
        NSString *currentTimeStr = [NSString stringWithFormat:@"%02d:%02d", (int)current / 60, (int)current % 60];
        NSString *timeStr = [NSString stringWithFormat:@"%@/%@", currentTimeStr, durrationTimeStr];
        self.timeLable.text = timeStr;
        
        //Slider的value
        self.progressSlider.value = current / duration;
        
    }];
}

/** 播放按钮事件 */
- (void)playButtonAction:(UIButton *)button {
    if(self.isPlay == YES) {
        [self.player pause];
        [self.playButton setImage:[UIImage imageNamed:@"videoplayer_play@2x.png"] forState:UIControlStateNormal];
    }else {
        [self.player play];
        [self.playButton setImage:[UIImage imageNamed:@"videoplayer_pause@2x.png"] forState:UIControlStateNormal];
        
    }
    self.isPlay = !self.isPlay;
}


/** 进度条滑竿事件 */
- (void)progressSliderAction:( UISlider *)Slider {
    //获取 UISlider对象
    UISlider *slider = Slider;
    //获取 当前进度时间
    CGFloat currentTiem = self.totalDuration * slider.value;
    //转化为 CMTime
    CMTime dragTime = CMTimeMake(currentTiem, 1);
    
    [self.player seekToTime:dragTime completionHandler:^(BOOL finished) {
        //到了那个时间之后，开始播放
        [self.player play];
    }];
}

/** 隐藏底部视图 */
- (void)hidentBottomView {
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(hidentBottomViewTapAction:)];
    [self.playView addGestureRecognizer:tap];
    
}
/** 点击屏幕隐藏按钮 */
- (void)hidentBottomViewTapAction:(UITapGestureRecognizer *)sender
{
    if (self.isHideen == NO) {
        [UIView animateWithDuration:1 animations:^{
            self.bottomView.alpha = 0;
            _downLoadButton.alpha = 0;
            
            
        }completion:^(BOOL finished) {
            self.bottomView.hidden = YES;
            
        }];
    }else {
        self.bottomView.alpha = 1;
        _downLoadButton.alpha = 1;
        self.bottomView.hidden = NO;
        
        
    }
    self.isHideen = !self.isHideen;
    
}

//视图即将消失时 关闭视频播放器
-(void)viewWillDisappear:(BOOL)animated{
    
    [super viewWillDisappear:animated];
    
    [self.player pause];
    
    [self.player replaceCurrentItemWithPlayerItem:nil];
    [self.playerLayer removeFromSuperlayer];
    _playerLayer = nil;
    _playerItem = nil;
    _player = nil;
    
}
#pragma mark - 协议跳转
- (void)imagePush:(ZLAllVideoDetailModel *)model {
    ZLHeadDetailViewController *headVc = [[ZLHeadDetailViewController alloc] init];
    [self.navigationController pushViewController:headVc animated:NO];
    headVc.model = model;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
